﻿var countUploadedImages = 0;
var total = 0;
var uploadedCount = 0;

$(document).ready(function () {
    $("#btnUploadImage").change(handleUpload);

    $("#btnBack").click(handleBack);

    $("#btnDelete").click(handleDelete);

    $("#btnSave").click(handleSave);
});

var handleBack = function (event) {
    var controler = "Master";
    var action = "Main";
    var goBack = $("#goBack").val();
    var arr = goBack.split(";");
    var groupId = "";
    var subGroupId = "";

    if (goBack.length >= 2) {
        groupId = arr[0];
        subGroupId = arr[1];
    }

    var param = "pageIndex=1&groupId=" + groupId + "&subGroupId=" + subGroupId;

    redirectToPage(controler, action, param);
}

var handleSave = function (event) {
    var length = $(".productinfo").length;
    if (length <= 0) {
        alert("Chưa tải hình ảnh và thông tin sản phẩm!");
    }
    else {
        var data = {};
        var products = [];

        $(".infodiv").each(function () {
            var index = $(this).attr("index");
            var product = {};
            product.Price = $('.price[index=' + index + ']').val();
            product.Qty = $('.qty[index=' + index + ']').val();
            product.Description = $('.description[index=' + index + ']').val();
            product.Materials = $('.material[index=' + index + ']').val();
            product.FreeService = $('.freeService[index=' + index + ']').val();
            product.FeeService = $('.feeService[index=' + index + ']').val();

            var object = { index: index, product: product };

            products.push(object);
        });

        data.itemGroup = $("#hdnItemGroup").val();
        data.subItemGroup = $("#hdnSubItemGroup").val();
        data.products = JSON.stringify(products);

        $.ajax({
            type: "POST",
            url: "/Master/Save",
            async: false,
            data: data,
            dataType: "json",
            success: function (data) {
                // console.log(data);
                if (data == null || data == ERROR_PAGE) {
                    alert("Thêm sản phẩm đã xảy ra lổi, hãy thử lại.");
                }
                else if (data == LOST_SESSION) {
                    redirectToLogin();
                }
                else if (data == PAGE_OK) {
                    $("#btnBack").click();
                }
            }
        });
    }
}

var handleDelete = function (event) {
    $("div.selected").remove();
    $("#btnDelete").addClass("disabled").attr("disabled", "disabled");
}

var handleClickImage = function (event) {
    // var action = "/Master/LoadImage";
    // var param = 
    var action = "/Master/LoadAllThumnail";
    /*
    var groupId = $(this).attr("groupId");
    var subGroupId = $(this).attr("subGroupId");
    var productId = $(this).attr("productId");
    var param = "?groupId=" + groupId + "&subGroupId=" + subGroupId +
        "&productId=" + productId;
    */
    var param = "?index=" + $(this).find("img").attr("index");
    $("#toPopup").removeClass("mediumSize").addClass("largeSize");
    $("#popup").removeClass("mediumSize").addClass("largeSize");
    $("#popup").attr("src", action + param);
    showPopup();
    return false;
}

var handleClickRecord = function (event) {
    if ($("input").is(":focus") || $("textarea").is(":focus")) {
        return false;
    }

    if ($(this).hasClass("selected")) {
        $(this).removeClass("selected");
    }
    else {
        $(this).addClass("selected");
    }

    $(this).find("table").unbind("click");

    if ($("div.selected").length > 0) {
        $("#btnDelete").removeClass("disabled").removeAttr("disabled");
    }
    else {
        $("#btnDelete").addClass("disabled").attr("disabled", "disabled");
    }
}

var handleUpload = function (event) {
    event.preventDefault();
    event.stopPropagation();
    var fileInput = document.getElementById("btnUploadImage");

    if (fileInput.files.length == 0) {
        return;
    }

    var index = '';
    var uploadNewIndex = true;

    $(".selected").each(function () {
        index += $(this).attr("index") + ";";
        uploadNewIndex = false;
    });

    if (!uploadNewIndex) {
        total = $(".selected").length;
        uploadedCount = 0;
        loading();
    }

    for (var i = 0; i < fileInput.files.length; i++) {

        var request = new XMLHttpRequest();

        if (uploadNewIndex) {
            index = (i + countUploadedImages);
        }

        var data = new FormData();
        data.append("file", fileInput.files[i]);
        data.append("index", index + ";");

        processUpload(request, index, uploadNewIndex);

        request.upload.addEventListener('error', function (event) {
            // alert("error");
            console.log(event);
        });

        request.open("POST", "/Master/Upload");
        request.setRequestHeader("Cache-Control", "no-cache");

        request.send(data);
    }
}

/**
 * Download thumnail image when upload finish
 */
function handleHttpResponse(request, index) {
    if (request.readyState == 4) {
        if (request.status == 200) {
            var data = request.responseText;

            if (data != null && data != "") {
                showImageThumnail(data, index);
                // console.log(data);
            }
        }

    }
}

/**
  * Upload image
  */
function processUpload(request, index, isNewIndex) {
    var productInfo = '';

    if (isNewIndex) {
        // Create new div productinfo
        productInfo = $(
            '<div class="productinfo" index="' + index + '">' +
                '<div class="imagediv" index="' + index + '">' +
                    '<div id="progress_' + index + '" class="progress">' +
                        '<div class="bar"></div>' +
                        '<div class="percent"></div>' +
                    '</div>' +
                '</div>' +
                '<div class="infodiv" index="' + index + '"><table></table></div>' +
            '</div>');

        $(productInfo).click(handleClickRecord);

        $(".imageinfo").append(productInfo);

        request.onreadystatechange = function () {
            handleHttpResponse(request, index);
        }

    }

    // Create progress bar and calculating uploaded percent
    request.upload.addEventListener('progress', function (event) {
        if (event.lengthComputable) {
            var uploadPercent = Math.round((parseFloat(event.loaded / event.total) * 100)) + PERCENT;

            if (isNewIndex) {
                var progress = $("#progress_" + index);
                var bar = $(progress).find(".bar");
                var percent = $(progress).find(".percent");

                $(bar).css("width", uploadPercent);
                $(percent).text(uploadPercent);
            }
            else {
                if (uploadPercent == UPLOADED_PERCENT) {
                    uploadedCount++;

                    if (uploadedCount == total) {
                        enablePage();
                    }
                }
            }
        }
    });
}

/**
  * Show block to edit info
  */
function showImageThumnail(data, index) {
    if (data == null || data == "") {
        return;
    }

    var image = $(
            '<a href="#"><img src="" alt="" class="image" index="' + index + '" imageid="' + index + '"/></a>');

    setImageUrl(data, index);

    $(image).click(handleClickImage);

    var imagediv = $('.imagediv[index=' + index + ']').empty().append(image);

    var tableInfo = $('.infodiv[index=' + index + ']').find("table").empty();
    $(tableInfo).append(getTableTr("Giá: ", "price", index, true, VALIDATE_NUMBER));
    $(tableInfo).append(getTableTr("Số lượng: ", "qty", index, true, VALIDATE_NUMBER));
    $(tableInfo).append(getTableTr("Mô tả: ", "description", index, true, VALIDATE_MAXLENGTH, 500));
    $(tableInfo).append(getTableTr("Nguyên liệu: ", "material", index, true, VALIDATE_MAXLENGTH, 150));
    $(tableInfo).append(getTableTr("Dịch vụ miễn phí: ", "freeService", index, false, VALIDATE_MAXLENGTH, 500));
    $(tableInfo).append(getTableTr("Dịch vụ tính phí: ", "feeService", index, false, VALIDATE_MAXLENGTH, 500));

    countUploadedImages++;

    $("ul.productinfo li").click(function () {
        if ($(this).hasClass("selected")) {
            $(this).removeClass("selected");
        }
        else {
            $(this).addClass("selected");
        }
    });
}

function getTableTr(title, name, index, isTextBox, classToValidate, maxLength) {
    classToValidate = classToValidate == null ? "" : classToValidate;
    maxLength = maxLength == null ? "" : maxLength;
    var div = $('<tr>' + 
                    '<td>' + title + '</td>' +
                    '<td>' +
                        (isTextBox == null || isTextBox ?
                        '<input type="text" class="text ' + classToValidate + ' ' + name + '" index="' + index + '" />' :
                        '<textarea class="textarea ' + name + '" index="' + index + '" maxlength="' + maxLength + '" />'
                        ) +
                    '</td>' +
                '</tr>');
    return div;
}

/**
  * Process blob to Image Url
  */
function setImageUrl(path, index) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            // this.response is what you're looking for
            // handler(this.response);
            // console.log(this.response, typeof this.response);
            var img = document.getElementById('img');
            var url = window.URL || window.webkitURL;
            $('.image[index=' + index + ']').attr("src", url.createObjectURL(this.response));
        }
    }
    xhr.open('GET', path);
    xhr.responseType = 'blob';
    xhr.send();
}